package com.lm.controller;

import com.lm.model.LmProductCash;
import com.lm.model.LmTrackEvent;
import com.lm.service.KwOperationLogService;
import com.lm.service.LmProductCashService;
import com.lm.service.LmTrackEventService;
import com.meirengu.common.RedisClient;
import com.meirengu.common.StatusCode;
import com.meirengu.controller.BaseController;
import com.meirengu.model.Result;
import com.meirengu.utils.DateUtils;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.text.SimpleDateFormat;
import java.util.*;

@RequestMapping("lmSchedule")
@Controller
public class ScheduleController extends BaseController {

    @Autowired
    private LmProductCashService lmProductCashService;
    @Autowired
    private LmTrackEventService lmTrackEventService;
    @Autowired
    private RedisClient redisClient;
    @Autowired
    private KwOperationLogService kwOperationLogService;

    Logger logger = LoggerFactory.getLogger(ScheduleController.class);


    /**
     * 定时增加贷款超市点击表格
     */
    @RequestMapping("scheduledLmTrack")
    @ResponseBody
    public Result scheduledLmTrack(@RequestParam(value = "jobDate", required = false) String jobDate) {
        Result result = new Result();
        try {
            Map<String, Object> paramMap = new HashMap<>();
            paramMap.put("status", 1);
            Calendar calendar = Calendar.getInstance();
            if (StringUtils.isNotBlank(jobDate)) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                calendar.setTime(sdf.parse(jobDate));
            }
            calendar.add(Calendar.DAY_OF_YEAR, 1);
            Date logTimeBegin = DateUtils.getDayBeginTime(calendar.getTime());
            Date logTimeEnd = DateUtils.getDayEndTime(calendar.getTime());
            List<LmProductCash> lmProList = lmProductCashService.getModel(paramMap);
            kwOperationLogService.addOperationLog("2", "定时增加贷款超市点击表数据", "scheduledLmTrack",
                    "定时任务", DateUtils.dateToStr(logTimeBegin), DateUtils.dateToStr(logTimeEnd), "lmTrackEvent", 0,
                    null, null, null);
            if (lmProList.size() > 0) {
                for (LmProductCash lmProductCash : lmProList) {
                    LmTrackEvent lmTrackEvent = new LmTrackEvent();
                    lmTrackEvent.setCreateDate(new Date());
                    lmTrackEvent.setProductName(lmProductCash.getProductName());
                    lmTrackEvent.setAction("跳转");
                    lmTrackEvent.setProductId(lmProductCash.getId());
                    lmTrackEvent.setPresetNum(lmProductCash.getPresetNum());
                    lmTrackEvent.setPresetUv(lmProductCash.getPresetUv());
                    lmTrackEvent.setPv(0);
                    lmTrackEvent.setUv(0);
                    lmTrackEvent.setNewuv(0);
                    lmTrackEvent.setDataDate(calendar.getTime());
                    lmTrackEventService.insert(lmTrackEvent);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(ExceptionUtils.getFullStackTrace(e));
            logger.error(">> LmScheduleController.scheduledLmTrack throw exception: {}", e);
            result.setCode(StatusCode.INTERNAL_SERVER_ERROR);
            return result;
        }
        result.setCode(StatusCode.OK);
        return result;
    }

    /**
     * 定时还原redis点击数
     */
    @RequestMapping("redisRestore")
    @ResponseBody
    public Result redisRestore() {
        Result result = new Result();
        Calendar calendar = Calendar.getInstance();
        Date logTimeBegin = DateUtils.getDayBeginTime(calendar.getTime());
        Date logTimeEnd = DateUtils.getDayEndTime(calendar.getTime());
        try {
            Map<String, Object> map = new HashMap<>();
            map.put("limitPreset", "Y");
            List<LmProductCash> list = lmProductCashService.getModel(map);
            kwOperationLogService.addOperationLog("2", "接口限制数量还原", "lmRedisRestore",
                    "定时任务", DateUtils.dateToStr(logTimeBegin), DateUtils.dateToStr(logTimeEnd), "redisRestore", 0,
                    null, null, null);
            if (list.size() > 0) {
                for (LmProductCash lmProductCash : list) {
                    redisClient.hset("product_preset", "preset_num_" + lmProductCash.getId(), String.valueOf(lmProductCash.getPresetNum()));
                    redisClient.hset("product_preset", "out_preset_" + lmProductCash.getId(), "N");
                    redisClient.hset("product_preset", "limit_preset_" + lmProductCash.getId(), "Y");
                }
            }
        } catch (Exception e) {
            String params = String.format("参数：redisRestore:%s",
                    "接口限制数量还原错误");
            logger.error(">> ScheduleController.redisRestore throw exception: {} happens. params:{}.", ExceptionUtils.getFullStackTrace(e), params);
            result.setCode(StatusCode.INTERNAL_SERVER_ERROR);
            return result;
        }
        result.setCode(StatusCode.OK);
        return result;
    }

    /**
     * 初始化redis点击数
     */
    @RequestMapping("redisInit")
    @ResponseBody
    public Result redisInit() {
        Result result = new Result();
        try {
            Map<String, Object> map = new HashMap<>();
            List<LmProductCash> list = lmProductCashService.getModel(map);
            if (list.size() > 0) {
                for (LmProductCash lmProductCash : list) {
                    redisClient.hset("product_preset", "preset_num_" + lmProductCash.getId(), "999");
                    redisClient.hset("product_preset", "out_preset_" + lmProductCash.getId(), "N");
                    redisClient.hset("product_preset", "limit_preset_" + lmProductCash.getId(), "N");
                }
            }
        } catch (Exception e) {
            String params = String.format("参数：redisRestore:%s",
                    "接口限制数量还原错误");
            logger.error(">> ScheduleController.redisRestore throw exception: {} happens. params:{}.", ExceptionUtils.getFullStackTrace(e), params);
            result.setCode(StatusCode.INTERNAL_SERVER_ERROR);
            return result;
        }
        result.setCode(StatusCode.OK);
        return result;
    }
}
